#include "aerial\CreateScene.h"
// scene change
#include "aerial\MainMenuScene.h"
//guiobject
#include "aerial\Object\Button.h"
#include "aerial\Object\Panel.h"

#include "aerial\Scene\Event.h"
#include "aerial\Core\Core.h"

#include "platform\PlatFormMessage.h"


bool CreateScene::initialize()
{
	received = true;
	Panel* menu = new Panel(hgeResMan, 0, 0, 250, 600);
	if (netIO->server)
	{
		menu->placeGuiObjectOffset(
			new Button(hgeResMan, 0.5f, "Start",
				new SEvent<CreateScene>(this, &CreateScene::start)
			), 
			40.0f, 120.0f);
	}

	menu->placeGuiObjectOffset(
		new Button(hgeResMan, 0.5f, "Back",
			new SEvent<CreateScene>(this, &CreateScene::back)
		), 
		40.0f, 220.0f);
	menu->addToGui(sceneManager);

	Panel* mainPanel = new Panel(hgeResMan, 210.f, 40.f, 210.1f, 40, 550, 500);

	menu->addToGui(sceneManager);
	mainPanel->addToGui(sceneManager);
	return true;
}

void CreateScene::start()
{
	
}

void CreateScene::back()
{
	sceneManager->setNextScene(new MainMenuScene());
	setSceneEnd();
	//MessageBox(NULL, L"Button Pressed", L"A.I.R", MB_OK);
}

bool CreateScene::update(float dt)
{
	Packet* p;
	if (p = netIO->m_recv()) {
		PlatformMessageCreate pmc;
		PlatformMessageJoin pmj;
		BitStream bso;
		BitStream bsi(p->data, p->length, false);
		switch (p->data[0])
		{
		case ID_CONNECTION_LOST:
			netIO->inTouchWithServer = false;
			cout << "remote server lost.\n";
			break;
		case ID_CONNECTION_REQUEST_ACCEPTED:
			netIO->inTouchWithServer = true;
			break;
		case ID_CONNECTION_ATTEMPT_FAILED:
			netIO->inTouchWithServer = false;
			cout << "id_connection_attempt_failed.\n";
			break;
		case ID_CHECK_ROOM:
			if (!netIO->DeSerializationPlayerInfo(&bsi)) {
				cout << "corrupted.\n";
			}
			received = true;
			break;
		default:
			cout << "unhandled packet head " << (int)p->data[0] << endl;
		}
		netIO->Deallocate(p);
	}
	++updateCount;
	if (updateCount >= 60) {
		if (received && netIO->inTouchWithServer) {
			BitStream bso;
			PlatformMessageJoin pmj;
			pmj.roomname = roomName;
			pmj.username = netIO->username;
			bso.Write((uchar)ID_CHECK_ROOM);
			pmj.Serialization(&bso, true);
			netIO->sendToMainServer(&bso);
			received = false;
		}
		updateCount = 0;
	}
	return false;
}

bool CreateScene::render(float dt)
{
	hge->Gfx_Clear(0xffffffff);
	acc->Render();
	gui->Render();
	return false;
}


void CreateScene::Enter() 
{
	gui->Enter();
}

void CreateScene::Leave() 
{
	gui->Leave();
}
